package com.zhixi.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.zhixi.mapper.UserMapper;
import com.zhixi.pojo.User;
import com.zhixi.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class UserController {

    @Resource
    private UserMapper userService;

    /**
     * 登录接口
     * @param user 表单传来的user数据
     * @return 登录信息
     */
    @PostMapping("/user/login")
    public Map<String, Object> login(User user) {
        log.info("用户名：{}", user.getName());
        log.info("password: {}", user.getPassword());

        Map<String, Object> map = new HashMap<>();

        try {
            // 查询数据库
            User userDb = userService.login(user);
            if (userDb == null) {
                throw new RuntimeException("用户名或密码错误");
            }
            Map<String, String> payload = new HashMap<>(16);
            payload.put("id", Long.toString(userDb.getId()));
            payload.put("name", userDb.getName());
            String token = JWTUtil.createToken(payload);
            log.info("token: {}", token);
            map.put("state", true);
            map.put("msg", "登录成功");
            map.put("token", token);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("state", false);
            map.put("msg", e.getMessage());
            map.put("token", "");
        }
        return map;
    }

    /**
     * 拦截器进行验证的测试接口
     * @param request 请求
     * @return 接口的返回的jwt数据数据
     */
    @PostMapping("/user/test")
    public Map<String, Object> test(HttpServletRequest request) {
        String token = request.getHeader("token");
        DecodedJWT verify = JWTUtil.verify(token);

        String id = verify.getClaim("id").asString();
        String name = verify.getClaim("name").asString();
        log.info("用户id：{}", id);
        log.info("用户名: {}", name);

        //TODO 业务逻辑
        Map<String, Object> map = new HashMap<>();
        map.put("state", true);
        map.put("msg", "请求成功");
        return map;
    }

}
